<template>
	<view class="bg-white px-3">
		<uni-forms label-width="200" :model="form" ref="uForm" label-position="top">
			<div class="flex flex-column">
				<div class="flag-title fte87722">基础信息</div>
				<uni-forms-item required :border-bottom="false" name="goods_name" label="商品名称"><input v-model="form.goods_name"
						placeholder="请输入内容" /></uni-forms-item>
				<uni-forms-item required :border-bottom="false" name="goods_classify_id" label="商品分类">
					<view class="flex align-center border px-2 py-1 bgf7f7f7 rounded" @tap="pickershow = true">
						<text class="flex-1 fs-28">{{form.goods_classify_id?form.classText:'选择商品分类'}}</text>
						<uni-icons class="ft999999" type="down"></uni-icons>
					</view>
				</uni-forms-item>
				<uni-forms-item :border-bottom="false" name="stock" label="库存"><input v-model="form.stock" type="number"
						placeholder="请输入内容" /></uni-forms-item>
				<uni-forms-item :border-bottom="false" name="brand" label="商品品牌"><input v-model="form.brand"
						placeholder="请输入内容" /></uni-forms-item>
				<div class="flag-title fte87722">价格信息</div>
				<uni-forms-item required :border-bottom="false" name="day_amount" label="日租金额(元)"><input
						v-model="form.day_amount" placeholder="请输入内容" /></uni-forms-item>
				<uni-forms-item required :border-bottom="false" name="deposit_amount" label="押金金额(元)"><input
						v-model="form.deposit_amount" placeholder="请输入内容" /></uni-forms-item>
				<uni-forms-item required :border-bottom="false" name="buyed_amount" label="买断金额(元)"><input
						v-model="form.buyed_amount" placeholder="请输入内容" /></uni-forms-item>
				<div class="flag-title fte87722">详情信息</div>
				<uni-forms-item required :border-bottom="false" name="main_image" label="商品主图">
					<u-upload :file-list="main_image" :header="{ 'ba-user-token': storage.getAccessToken(),server:true }"
						:action="action" width="200" @on-uploaded="onUploaded($event, 'main_image')" :max-count="1"
						:show-progress="false" @on-remove="removemainimage"></u-upload>
				</uni-forms-item>
				<uni-forms-item required :border-bottom="false" name="images" label="商品幻灯片">
					<u-upload :file-list="images" :header="{ 'ba-user-token': storage.getAccessToken(),server:true }"
						:action="action" width="200" @on-uploaded="onUploaded($event, 'images')" :max-count="6"
						:show-progress="false" @on-remove="removeImages"></u-upload>
				</uni-forms-item>

				<uni-forms-item required :border-bottom="false" name="detail_info" label="商品描述"
					style="margin-bottom: 0px;"></uni-forms-item>
				<!-- <view class="bgf7f7f7 p-2 rounded htmlContent vhtml" :class="htmlContent === '请输入商品描述'?'ft999999':''"
					style="max-height: 600px;min-height: 100rpx;" v-html="htmlContent" @click="navTo('/pages/store/goodsIntro')">
				</view> -->
				<view class="bgf7f7f7 rounded htmlContent vhtml position-relative">
					<uni-icons class="position-absolute top-0 right-0" style="margin-top: -35px;" type="compose" color="#e87722"
						size="25" @click="navTo('/pages/store/goodsIntro')"></uni-icons>
					<rich-text-with-video :html="htmlContent"></rich-text-with-video>
				</view>
			</div>
		</uni-forms>
		<view style="height: 100px;"></view>
		<view class="position-fixed bottom-0 left-0 right-0" style="z-index: 999;">
			<div class="rounded-circle text-center py-2 bge87722cc text-white fs-32 mx-3" @click="validatorStep1Form">提交审核
			</div>
			<view style="height: 40px;"></view>
		</view>

		<u-picker z-index="99999" mode="multiSelector" range-key="name" v-model="pickershow"
			:default-selector='selectedIndices' :range="rangeData" @confirm="handleChange"
			@columnchange="handleColumnChange"></u-picker>
	</view>
</template>

<script>
	import storage from "@/utils/storage.js";
	import {
		upload
	} from "@/api/common.js";
	import {
		createGoods,
		storeGoodsDetails,
		goodsUpdate
	} from "@/api/store.js";
	import {
		getCategoryList
	} from "@/api/goods.js";
	export default {
		data() {
			return {
				selectedIndices: [0, 0],
				htmlContent: '请输入商品描述',
				storage,
				action: upload, //图片上传数据
				defaultInputStyle: {
					background: "#f7f7f7",
					padding: "0 20rpx",
					"border-radius": "10rpx",
				},
				form: {
					goods_name: '',
					goods_classify_id: '',
					classText: '',
					day_amount: '',
					deposit_amount: '',
					detail_info: '',
					buyed_amount: '',
					images: [],
					main_image: [],
					stock: 100
				},
				images: [],
				main_image: [],
				typeList: [],
				rangeData: [
					[],
					[]
				],
				typeshow: false,
				goodsDetails: {},
				id: null,
				pickershow: false,
				columnIndex: 0,
			}
		},
		onLoad(query) {
			this.id = query.id || ''
		},
		onShow() {
			const goods_100 = uni.getStorageSync('goods_100')
			if (goods_100) {
				const html = goods_100.replace(
					/<img/g,
					`<img class="rich-img"`
				);
				this.htmlContent = html.replace(
					/<video/g,
					`<video class="rich-img"`
				);
				setTimeout(() => {
					uni.removeStorageSync('goods_100')
				}, 1000)
			}
			console.log(goods_100)
		},
		created() {
			this.getCategoryList()
		},
		methods: {
			navTo(url) {
				uni.setStorageSync('goods_htmlContent', this.htmlContent)
				setTimeout(() => {
					uni.navigateTo({
						url
					})
				})
			},
			storeGoodsDetails() {
				storeGoodsDetails({
					id: this.id
				}).then(res => {
					this.goodsDetails = res.data.goods
					this.form = {
						...this.goodsDetails,
						classText: this.findCategoryAndCombine(this.typeList, this.goodsDetails.goods_classify_id),
						main_image: [this.goodsDetails.main_image]
					}
					this.htmlContent = this.goodsDetails.detail_info.replace(
						/<img/g,
						`<img class="rich-img"`
					);
					this.images = this.goodsDetails.images.map(item => {
						return {
							url: item
						}
					})
					console.log('this.images', this.images)
					this.main_image = [{
						url: this.goodsDetails.main_image
					}]
				})
			},
			findCategoryAndCombine(jsonData, targetId) {
				// 递归遍历函数
				function traverse(items, parentName = null) {
					for (const item of items) {
						// 检查当前项是否是目标
						if (item.id === targetId) {
							// 如果有父名称则组合，否则只返回当前名称
							return parentName ? `${parentName}/${item.gd_c_name}` : item.gd_c_name;
						}

						// 如果有子项，递归查找
						if (item.children && item.children.length > 0) {
							const result = traverse(item.children, item.gd_c_name);
							if (result) {
								return result;
							}
						}
					}
					return null; // 未找到
				}

				return traverse(jsonData);
			},
			handleChange(e) {
				console.log(e)
				// const val = e.detail.value
				// console.log(this.rangeData)
				this.selectedIndices = e
				this.form.goods_classify_id = this.rangeData[1][this.selectedIndices[this.columnIndex]]['id']
				this.form.classText = this.getSelectedText()

			},
			getCategoryList() {
				getCategoryList().then(res => {
					this.typeList = res.data.list
					this.initRangeData()
					if (!this.id) return
					this.storeGoodsDetails()
				})
			},
			initRangeData() {
				// 1. 提取所有一级分类的 gd_c_name 作为第一列
				const firstColumn = this.typeList.map(item => {
					return {
						id: item.id,
						name: item.gd_c_name
					}
				});

				// 2. 提取默认一级分类（第0个）的 children 作为第二列
				const defaultSecondColumn = this.typeList[0].children.map(child => {
					return {
						id: child.id,
						name: child.gd_c_name
					}
				});


				// 组合为 range 数据（二维数组）
				this.rangeData = [firstColumn, defaultSecondColumn];
				console.log('this.rangeData---', this.rangeData)
			},
			// 当某一列滚动时触发（用于二级分类联动）
			handleColumnChange(e) {
				const {
					column,
					index
				} = e;
				console.log(e)
				// 仅处理第一列（一级分类）的滚动
				if (column === 0) {
					// 根据选中的一级分类索引，更新第二列数据
					const selectedFirstItem = this.typeList[index];
					const secondColumn = selectedFirstItem.children.map(child => {
						return {
							id: child.id,
							name: child.gd_c_name
						}
					});
					// 更新 rangeData 的第二列
					// this.rangeData.splice(1, 1, secondColumn)
					// this.rangeData[1] = secondColumn;
					this.rangeData = [this.rangeData[0], secondColumn]
					// 重置第二列的选中索引为 0（避免索引越界）
					this.selectedIndices[0] = index;
					this.selectedIndices[1] = 0;
				} else {
					this.columnIndex = column
					this.selectedIndices[column] = index;
				}
			},
			// 获取选中的文本（拼接一级和二级分类）
			getSelectedText() {
				const [firstIndex, secondIndex] = this.selectedIndices;
				const firstText = this.rangeData[0][firstIndex].name || "";
				const secondText = this.rangeData[1][secondIndex].name || "";
				return `${firstText}/${secondText}`;
			},
			onUploaded(lists, key) {
				let images = [];
				if (!this.form[key]) {
					this.form[key] = [];
				}
				console.log(lists)
				const list = lists.filter(item => item.response)
				list.forEach((item) => {
					images.push(item.response.data.file.url);
				});
				// console.log(images, key)
				if (key === 'main_image') {
					this.form[key] = images
					return
				}
				this.form[key].push(...images);
				// console.log(this.form)
			},
			removeImages(index) {
				this.form['images'].splice(index, 1)
			},
			removemainimage(index) {
				this.form['main_image'].splice(index, 1)
			},
			validatorStep1Form() {
				this.form.detail_info = this.htmlContent
				const data = JSON.parse(JSON.stringify(this.form))
				delete data.brand;
				const flag = Object.keys(data).some(key => !data[key] && data[key] != 0)
				console.log('this.form-----', data)
				if (flag) {
					uni.showToast({
						title: '请完善商品信息',
						icon: 'none'
					})
					return
				}
				uni.showLoading({
					title: '提交商品中...'
				})
				this.createGoods()
			},
			createGoods() {
				const params = {
					...this.form
				};
				params.main_image = this.form.main_image.join(',')
				// console.log(params, this.form.main_image)
				if (params.id) {
					this.goodsUpdate(params)
					return
				}

				createGoods(params).then(res => {
					const data = res
					if (data.code !== 1) {
						uni.showToast({
							title: data.msg,
							icon: 'none'
						})
						return
					}
					setTimeout(() => {
						uni.showToast({
							title: '创建商品成功'
						})
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/store/goodsManage'
							})
						}, 1500)
					}, 2000)
				})
			},
			goodsUpdate(params) {
				goodsUpdate(params).then(res => {
					const data = res
					if (data.code !== 1) {
						uni.showToast({
							title: data.msg,
							icon: 'none'
						})
						return
					}
					setTimeout(() => {
						uni.showToast({
							title: data.msg
						})
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/store/goodsManage'
							})
						}, 1500)
					}, 2000)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.column {
		padding: 32rpx;
		margin-bottom: 20rpx;
		background: #fff;
	}

	.tips {
		color: #999;
		font-size: 24rpx;
		line-height: 1.2;
		margin-top: 10rpx;
	}

	.flag-title {
		font-size: 42rpx;
		font-weight: bold;
	}

	.submit,
	.notice {
		font-weight: bold;
		font-size: 28rpx;

		height: 92rpx;
		text-align: center;
		letter-spacing: 4rpx;
		line-height: 92rpx;
		border-radius: 20rpx;
	}

	.wrapper {
		padding: 16rpx;
	}
</style>